<template>
  <van-nav-bar title="购物车" fixed placeholder />
  <div class="list">
    <div class="item" v-for="item in cartArr" :key="item.cartid">
      <van-checkbox v-model="item.flag" @click="onSelectOne(item)"></van-checkbox>
      <van-image width="100" height="100" :src="item.img1" />
      <span>{{ item.originprice }}</span>
      <van-stepper v-model="item.num" @change="onCartNumChange(item)" />
      <van-button type="danger" @click="onCartDel(item.cartid)">删除</van-button>
    </div>
  </div>
  <van-submit-bar :price="allPrice" button-text="提交订单" @submit="onSubmit">
    <!-- checkbox不用change事件， 修改 allSelected变量的值，又触发 change事件-->
    <van-checkbox v-model="allSelected" @click="onAllSelectChange">全选</van-checkbox>
    <template #tip> 你的收货地址不支持配送, <span @click="onClickLink">修改地址</span> </template>
  </van-submit-bar>
</template>
<script>
import {
  cartDelAPI,
  cartListAPI,
  cartSingleSelectedAPI,
  cartUpdateNumAPI,
  cartAllSelectedAPI,
} from "@/api/cart";
import { getCartList } from "@/store/cart";

export default {
  data() {
    return {
      cartArr: [],
      allSelected: false,
    };
  },
  computed: {
    allPrice() {
      let sum = this.cartArr
        .filter((v) => v.flag == true)
        .reduce((sum, v) => sum + v.num * v.originprice * 100, 0);
      console.log(sum);
      return sum;
    },
  },
  watch: {
    cartArr: {
      deep: true,
      immediate: true,
      handler() {
        console.log("cartArr的改变");
        if (this.cartArr.length == 0) {
          this.allSelected = false;
        } else {
          this.allSelected = this.cartArr.every((v) => v.flag == true);
        }
      },
    },
  },
  methods: {
    onSubmit() {},
    onClickLink() {},
    async onAllSelectChange() {
      console.log("onAllSelectChange");
      // 调用全选接口
      await cartAllSelectedAPI(this.allSelected);
      console.log(this.allSelected);
      this.loadList();
    },
    async onCartDel(cartid) {
      await cartDelAPI(cartid);

      this.loadList();
    },
    async loadList() {
      // let r = await cartListAPI();
      // console.log(r.data);
      getCartList().then((r) => {
        // r 就是 getCartList函数中return 的值
        this.cartArr = r;
      });

      // this.cartArr = r.data.data;
    },
    async onCartNumChange(item) {
      await cartUpdateNumAPI(item.cartid, item.num);
      this.loadList();
    },
    async onSelectOne(item) {
      await cartSingleSelectedAPI(item.cartid, item.flag);
      this.loadList();
    },
  },
  async mounted() {
    this.loadList();
  },
};
</script>
<style lang="css" scoped>
.van-submit-bar {
  bottom: 50.1px;
}
.list {
  padding-bottom: 85px;
}
</style>
